package com.angus.auth.service.front;

import com.angus.common.security.config.SendCodeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author liyanan
 * @date 2025/06/17 下午4:24
 * @description 
 */
@Component
@Slf4j
public class EmailSendService {

    @Autowired
    private SendCodeConfig sendCodeConfig;

    @Value("${send-code.mail.username}")
    private String from;

    @Value("${send-code.mail.subject}")
    private String subject;

    @Value("${send-code.mail.contentTemplate}")
    private String contentTemplate;

    public void sendEmailCode(String to, String code) {
        MimeMessage message = sendCodeConfig.javaMailSender().createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // 构建邮件内容，使用HTML格式
            helper.setText(String.format(contentTemplate, code), true);
            // 发送邮件
            sendCodeConfig.javaMailSender().send(message);
        } catch (MailSendException e) {
            log.error("邮件发送失败: {}", e.getMessage());
            // 获取具体失败原因（可能包含多个地址的发送结果）
            Exception[] messageExceptions = e.getMessageExceptions();
            for (Exception ex : messageExceptions) {
                log.error("具体失败原因: {}", ex.getMessage());
            }
            throw new RuntimeException("邮件发送失败", e);
        } catch (MessagingException e) {
            log.error("邮件发送过程中发生未知异常: {}", e.getMessage(), e);
            throw new RuntimeException("邮件发送过程中发生未知异常", e);
        }
    }
}
